<template>
  <video :style="{ height: height, width: width }" :id="id" controls autoplay ref="video"></video>
</template>
<script>
// import $ from 'jquery'
import SrsRtcPlayerAsync from './utils/WebRTC'

export default {
  name: 'WebRTCPlayer',
  props: {
    id: {
      type: String,
      default: 'player'
    },
    url: {
      type: String,
      default: ''
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '100%'
    }
  },
  data () {
    return {
      sdk: null
    }
  },
  mounted () {
    this.startPlay()
  },
  watch: {},
  methods: {
    startPlay () {
      var video = document.getElementById(this.id)
      video.style.display = 'block'

      // Close PC when user replay.
      if (this.sdk) {
        this.sdk.close()
      }

      this.sdk = new SrsRtcPlayerAsync()
      this.sdk.onaddstream = function (event) {
        console.log('Start play, event: ', event)
        video.srcObject = event.stream
      }

      // For example:
      //      webrtc://r.ossrs.net/live/livestream
      var url = this.url
      this.sdk.play(url).then(function (session) {
        console.log('session', session)
      }).catch(function (reason) {
        this.sdk.close()
        // $(this.id).hide();
        console.error(reason)
      })
    }
  }
}
</script>

<style scoped>
video {
  object-fit: fill;
}
</style>
